// Tierless
// Copyright © 2010 Alphora
// This file is licensed under a modified BSD-license (see tierless_license.txt).
using System;
using System.Runtime.Serialization;

namespace Tierless.Framework.Constraints.Common
{
	/// <summary>
	/// Enforces that a string has a valid length.
	/// </summary>
	[DataContract]
	public class StringLengthValid : ColumnConstraint
	{
		/// <summary>
		/// Constructs a new instance of the StringLengthValid constraint.
		/// </summary>
		/// <param name="entityTypeName">The name of the entity type on which the constraint will be placed.</param>
		/// <param name="columnName">The name of the column on which the constraint will be placed.</param>
		/// <param name="maxLength">The maximum number of characters allowed in the string.</param>
		public StringLengthValid(string entityTypeName, string columnName, int maxLength)
			: base
			(
				String.Format("{0}_{1}StringLengthValid", entityTypeName, columnName),
				entityTypeName,
				columnName,
				String.Format("Value must be no more than ({0}) characters in length.", maxLength)
			)
		{
			_maxLength = maxLength;
		}

		[DataMember]
		private int _maxLength;

		public int MaxLength
		{
			get { return _maxLength; }
		}

		protected override bool IsValid(ConstraintContext context)
		{
			return context.Entity[ColumnName].AsString.Length <= _maxLength;
		}
	}
}